<template>
  <div class="login">
    <div class="logon-content">
      <!-- 配置logo -->
      <img
        v-if="logoPath!==''"
        :src="logoPath"
        class="logo"
      >
      <!-- 默认logo -->
      <img
        v-else
        src="../../assets/logo.png"
        class="logo"
      >
    </div>
    <div class="content">
      <div class="user-info-username">
        <i class="jeicon jeicon-user-o" />
        <input
          ref="inputBlurName"
          v-model="loginInfo.phone"
          type="text"
          placeholder="手机号/账户"
          class="form-input"
        >
        <span
          v-show="hasLoginHistory"
          @tap="loginHistory(false)"
          class="user-list-span"
        >
          <i class="jeicon jeicon-angle-right user-list" />
        </span>
      </div>
      <div
        v-show="loginState"
        class="user-info-pwd"
      >
        <i class="jeicon jeicon-lock" />
        <input
          ref="inputBlurPassword"
          v-model="loginInfo.pwd"
          :type="showPwd ? 'password' : 'text'"
          @keyup.enter="login"
          placeholder="密码"
          class="form-input"
          maxlength="20"
        >
        <i
          :class="['jeicon','viewpwd',{
            'jeicon-eye': showPwd,
            'jeicon-eye-close': !showPwd
          }]"
          @tap="showPwd=!showPwd"
          class="jeicon viewpwd"
        />
      </div>
      <div
        v-show="!loginState"
        class="user-info-pwd-message"
      >
        <i class="jeicon jeicon-lock " />
        <input
          v-model="loginInfo.validateCode"
          type="number"
          placeholder="短信动态密码"
          class="form-input"
          oninput="if(value.length>6)value=value.slice(0,6)"
          maxlength="6"
          pattern="\d*"
        >
        <button
          @tap="getValidateCode"
          class="get-validate-code"
        >
          <span v-show="sendAuthCode">获取</span>
          <span v-show="!sendAuthCode">{{ auth_time }}s</span>
        </button>
      </div>
      <div class="pwd">
        <label
          v-show="loginState"
        ><input
          v-model="remberStatus"
          type="checkbox"
          style="vertical-align:middle"
        ><span style="vertical-align:middle;">记住密码</span></label>
        <label
          v-show="loginState"
          @tap="loginState=!loginState,loginInfo.validateCode='',showPwd=true;"
        >动态密码登录</label>
        <label
          v-show="!loginState"
          @tap="loginState=!loginState,loginInfo.pwd=''"
        >个人密码登录</label>
        <label @tap="forgetPwd">忘记密码？</label>
      </div>
      <button
        ref="loginBtn"
        @tap="login"
        data-loading-text="登录中..."
        class="login-btn mui-btn "
      >
        登录
      </button>
      <!-- <span class="register-btn">
        <span @tap="register">立即注册</span>
      </span> -->
      <div class="other-login">
        <i
          v-if="isApplicationExist('qq')"
          @tap="appLogin('qq')"
          class="jeicon  jeicon-qq"
        />
        <i
          v-if="isApplicationExist('weixin')"
          @tap="appLogin('weixin')"
          class="jeicon jeicon-weixin"
        />
        <!-- <i
          @tap="appDingTalkLogin"
          class="jeicon jeicon-dingding"
        /> -->
      </div>
    </div>
    <sel-company-list
      ref="selCompanList"
      :company-list="companyList"
      :state="loginState"
      :show-modal-flag="showModalFlag"
      :user-info="loginInfo"
      :app-login="appLoginInfo"
      @showFlag="showFlag"
      type="loginPage"
    >
      <div slot="modalTitle">
        选择企业
      </div>
    </sel-company-list>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  removeToken, setToken, getBeforeUrl, removeBeforeUrl,
} from '@/views/login/util/auth';
import { loginSuccess } from '@/views/login/util/loginSuccess';
import { decipherStr, authLogin } from '@/views/login/util/oauthLogin';
import { validate, toastValidate } from '../../../../util/validate';
import {
  fetchSendValidateCode,
  fetchSearchUserCode,
  fetchCheckValidate,
  fetchCreateState,
  fetchLogin,
} from '../../actions/login';

import selCompanyList from '../../components/selcompanyList/index';

// 授权页面传递过来的参数，表明需要授权
const IS_BIND = 1;
export default {
  name: 'Login',
  components: {
    'sel-company-list': selCompanyList,
  },
  data() {
    this.isBind = this.$route.query.isBind === IS_BIND; // 判断是否为授权绑定流程过来的用户
    this.userCode = this.$route.query.code; // 用户唯一标识
    return {
      loginState: true,
      showPwd: true,
      loginInfo: {},
      appLoginInfo: {},
      sendAuthCode: true,
      auth_time: 0,
      company: [],
      logoClick: 0,
      companyList: [],
      showModalFlag: false,
      tapcount: 1,
      remberStatus: true, // 记住密码默认为true
      logoPath: '',
    };
  },
  computed: {
    hasLoginHistory() {
      let loginHistory = [];
      if (JE.getLSItem('loginHistory')) {
        loginHistory = JSON.parse(JE.getLSItem('loginHistory')) || [];
      }
      return loginHistory.length > 0;
    },
  },
  created() {
    // 首页返回键处理
    // 处理逻辑：1秒内，连续两次按返回键，则退出应用；
    let first = null;
    // const oldBack = mui.back;
    mui.back = function back() {
      // 首次按键，提示‘再按一次退出应用’
      if (!first) {
        first = new Date().getTime();
        mui.toast('再按一次退出应用');
        setTimeout(() => {
          first = null;
        }, 1000);
      } else if (new Date().getTime() - first < 1000) {
        plus.runtime.quit();
      }
    };
    this.getApkImg();
    this.valiBindParams();
    Waves.init();
  },
  mounted() {
    if (JE.getLSItem('phone') && JE.getLSItem('password')) {
      this.$set(this.loginInfo, 'phone', decipherStr(JE.getLSItem('phone')));
      this.$set(this.loginInfo, 'pwd', decipherStr(JE.getLSItem('password')));
    }
    this.loginHistory(true);
  },
  methods: {
    getApkImg() {
      const config = JE.getApkConfig('APP_LOGIN_ICO');
      const imgKey = config && config.split('*')[1];
      const imgName = config && config.split('*')[0];
      const reg = /\.(png|jpg|gif|jpeg|webp)$/;
      imgKey && reg.test(imgName) && (this.logoPath = JE.getLSItem(`loginPath_${JE.getApkCode()}`) || JE.buildURL(JE.getFileUrl(imgKey)));
    },
    /**
       * 验证是否携带全部需要绑定参数
       * 如果是授权流程但是没有用户code，则跳转至授权页面重新获取
       */
    valiBindParams() {
      if (this.isBind && !this.userCode) {
        this.$router.push('/auth');
        return false;
      }
    },
    isApplicationExist() {
    },
    // 展示公司列表
    showFlag() {
      this.showModalFlag = false;
      let timer = setTimeout(() => {
        this.btnReset();
      }, 10);
      timer = null;
    },
    // 登录记录，只获取前五
    loginHistory(init) {
      return;
      let loginHistory = [];
      const buttons = [];
      if (JE.getLSItem('loginHistory')) {
        loginHistory = JSON.parse(JE.getLSItem('loginHistory')) || [];
      }
      if (loginHistory.length > 5) {
        loginHistory = loginHistory.slice(0, 6);
      }
      for (let i = 0; i < loginHistory.length; i += 1) {
        buttons.push({ title: loginHistory[i] });
      }
      if (init) {
        this.$set(this.loginInfo, 'phone', loginHistory[0]);
      }
      // 翟梓钦注释
      // plus.nativeUI.actionSheet({
      //   title: '请选择',
      //   cancel: '取消',
      //   buttons
      // }, (e) => {
      //   if (e.index > 0) {
      //     this.$set(this.loginInfo, 'phone', buttons[e.index - 1].title);
      //   }
      // });
    },
    // 登录
    async login() {
      // 页面失去焦点
      mui('.mui-btn')
        .button('loading');
      Waves.attach('.login-btn', ['waves-button', 'waves-float']);
      if (!toastValidate('手机号', validate.isNull(this.loginInfo.phone))
          || (this.loginState && !toastValidate('密码', validate.isNull(this.loginInfo.pwd)))
          || (!this.loginState && !toastValidate('短信动态验证码', validate.isNull(this.loginInfo.validateCode)))) {
        mui('.mui-btn')
          .button('reset');
        return false;
      }
      // 校验验证码
      if (!this.loginState) {
        const validateCodeRes = await fetchCheckValidate({
          email: this.loginInfo.phone,
          type: 'PHONE',
          cz: 'LOGIN',
          code: this.loginInfo.validateCode,
        });
        if (!validateCodeRes.success) {
          mui.toast(validateCodeRes.message);
          mui('.mui-btn')
            .button('reset');
          return false;
        }
        // this.getCompanyList(this.loginInfo.phone);
        this.sendLogin('code', {
          j_username: this.loginInfo.phone,
          j_code: this.loginInfo.validateCode,
          state: '',
        });
      } else {
        // this.getCompanyList(this.loginInfo.phone, this.loginInfo.pwd);
        this.sendLogin('pwd', {
          j_username: this.loginInfo.phone,
          j_password: this.loginInfo.pwd,
        });
      }
    },
    // 发送登录
    async sendLogin(type, params) {
      let param = {};
      if (type === 'code') {
        param = {
          j_username: params.j_username,
          loginType: 'PHONE',
          j_code: params.j_code,
          state: params.state,
          isNew: 1,
          ...this.$thirdPlatform && this.$thirdPlatform.getLoginParams(),

        };
      } else if (type === 'pwd') {
        param = {
          j_username: params.j_username,
          j_password: params.j_password,
          isNew: 1,
          ...this.$thirdPlatform && this.$thirdPlatform.getLoginParams(),
        };
      }
      (this.isBind && window.plus) && (param = this.mergeBindParams(param));

      const res = await fetchLogin(param);
      if (res.success) {
        if (param.u && this.remberStatus) {
          JE.setLSItem('phone', param.u);
          JE.setLSItem('password', param.p);
        } else {
          localStorage.removeItem('phone');
          localStorage.removeItem('password');
        }
        if (res.code === 'OK') {
          setToken(res.obj);
          const loginPhone = this.loginInfo.phone || ';';
          if (loginPhone) {
            let set;
            if (JE.getLSItem('loginHistory')) {
              set = new Set(JSON.parse(JE.getLSItem('loginHistory')));
            } else {
              set = new Set();
            }
            set.add(loginPhone);
            JE.setLSItem('loginHistory', JSON.stringify(Array.from(set)));
          }
          // this.hideModal();
          // 登陆成功后传值给首页 请求接口渲染数据，渲染完成后回传登陆页关闭登陆页
          this.showModalFlag = false;
          this.$refs.inputBlurName.blur();
          this.$refs.inputBlurPassword.blur();
          this.$refs.inputBlurName.blur();
          this.$refs.inputBlurPassword.blur();

          // 登录成功，进行跳转
          loginSuccess(this);
          mui('.mui-btn')
            .button('reset');
        } else if (res.code === 'CHECK') {
          this.btnReset();
          this.showModalFlag = true;
          this.companyList = JSON.parse(res.obj);
        }
      } else {
        this.showModalFlag = false;
        this.btnReset();
        removeToken();
        mui.toast(res.message);
      }
    },
    // 合并绑定时候的参数
    mergeBindParams(params) {
      const platform = this.$thirdPlatform;
      const platformConfig = platform.getConfig();
      return Object.assign(params, {
        code: this.userCode,
        authLoginType: platformConfig.authType,
      });
    },
    // 查询公司列表  TODO 此方法暂时无用 可删除
    async getCompanyList(phone, pwd) {
      const params = {
        userCode: phone,
      };
      if (pwd) {
        params.password = pwd;
      }
      const userRes = await fetchSearchUserCode(params);
      if (userRes.success) {
        const companyList = JSON.parse(userRes.obj);
        this.company = companyList;
        if (companyList.length > 0) {
          const obj = companyList[0];
          if (obj.newLogin) {
            openWindow({
              url: './pages_firstLogin_index.html',
              id: '__firstLoginView',
              title: '登录',
              extras: {
                phone,
                deptName: obj.DEPTNAME,
                userName: obj.CREATEUSERNAME ? obj.CREATEUSERNAME : 'null',
                deptId: obj.DEPTID,
              },
            });
            /* this.$router.push({
                  name: 'firstLogin',
                  params: {
                    phone,
                    deptName: obj.DEPTNAME,
                    userName: obj.CREATEUSERNAME ? obj.CREATEUSERNAME : 'null',
                    deptId: obj.DEPTID,
                  },
                }); */
          } else {
            this.$refs.selCompanList.showModal(companyList);
          }
        }
      } else {
        mui.toast(userRes.msg);
      }
    },
    // 获取验证码
    async getValidateCode() {
      if (
        !toastValidate('手机号/账户', validate.isNull(this.loginInfo.phone))
          || !toastValidate('', validate.isPhone(this.loginInfo.phone), '手机号格式不正确')
      ) {
        return false;
      }

      if (this.sendAuthCode) {
        const res = await fetchSendValidateCode({
          email: this.loginInfo.phone,
          type: 'PHONE',
          cz: 'LOGIN',
        });
        mui.toast(res.message);
        if (res.success) {
          this.sendAuthCode = false;
          this.auth_time = 59;
          const auth_timetimer = setInterval(() => {
            this.auth_time--;
            if (this.auth_time <= 0) {
              this.sendAuthCode = true;
              clearInterval(auth_timetimer);
            }
          }, 1000);
        }
      }
    },
    // QQ/WX登录
    async appLogin(type) {
      if (!isApplicationExist(type == 'qq' ? 'qq' : 'weixin')) {
        mui.toast('请先登录此app');
        return;
      }
      // 调起三方之前发送状态机
      const stateRes = await fetchCreateState({
        type: 'PC',
        loginType: type == 'qq' ? 'QQ' : 'WX',
      });
        // 然后调起三方
      const res = await authLogin(type);
      // 请求返回
      if (JE.isNotEmpty(res)) {
        const pushInfo = JE.getPushInfo();
        const openId = res.authResult.openid;
        const loginRes = await fetchLogin({
          isNew: '1',
          state: stateRes.obj.STATE, // 发送状态机 返回state的值
          code: openId, // res.authResult.openid//第三方用户给的openID
          cid: pushInfo.clientid,
        });
        if (loginRes.success) {
          if (Array.isArray(loginRes.obj)) {
            mui('.mui-btn')
              .button('reset');
            this.$refs.selCompanList.showModal(loginRes.obj);
          } else {
            // this.showLoading=true;
            JE.setLSItem('authorization', loginRes.obj);
            plus && plus.webview.getLaunchWebview()
              .evalJS('APP.start.openHome()');
          }
        } else {
          // openWindow({
          //     url: './pages_register_1_index.html',
          //     id: '__register_1View',
          //     title: '注册',
          //     extras: {
          //       openid:openId,
          //       access_token:res.authResult.access_token,
          //       type:type == 'qq' ? 'QQ' : 'WX'
          //     },
          //   });
          // 此处暂时先关掉注册入口
          // mui.toast(loginRes.message);
          this.errorMsg(loginRes.errorCode, loginRes.message);
        }
      }
    },
    // 报错信息的弹框
    errorMsg(code, count) {
      const loginErrMsg = {
        1001: {
          cn1: '账号或者密码错误超过[',
          cn2: ']次,请使用其他方式登录!',
          en1: 'Account or password error more than [',
          en2: '] times, please use other way to log in!',
        },
        1002: {
          cn1: '账号或密码错误,您还剩余[',
          cn2: ']次个人密码登录机会!',
          en1: 'Account number or password error, you still have left [',
          en2: '] personal password login opportunity!',
        },
        1003: {
          cn: '验证码错误!',
          en: 'Verification code error!',
        },
        1004: {
          cn: '用户未认证!',
          en: 'User not authenticated!',
        },
        1005: {
          cn: '认证失败!',
          en: 'Authentication failed!',
        },
        1006: {
          cn: '帐号或密码错误!',
          en: 'Wrong account or password!',
        },
        1007: {
          cn: '状态机不对，请重新登录!',
          en: 'The state machine is not correct, please login again!',
        },
      };
      if ('1001,1002'.indexOf(code) > -1) {
        const cn = loginErrMsg[code].cn1 + count + loginErrMsg[code].cn2;
        mui.toast(cn);
      } else {
        mui.toast(loginErrMsg[code].cn);
      }
    },
    // 忘记密码
    forgetPwd() {
      this.$router.push({
        path: '/JE-PLUGIN-LOGIN/forget_pwd',
      });
    },
    // 注册
    /* register() {
          this.$refs.selCompanList.hideModal();
          openWindow({
            url: './pages_register_1_index.html',
            id: '__register_1View',
            title: '免费注册',
            extras: {
              type: 'SUANBAN',
            },
          });
        }, */
    btnReset() {
      this.$refs.inputBlurName.blur();
      this.$refs.inputBlurPassword.blur();
      mui('.mui-btn')
        .button('reset');
    },

  },
};
</script>
<style>
  .mui-btn .mui-spinner {
    width: 40px !important;
    height: 40px !important;
  }

  .mui-toast-container1 {
    bottom: 50px !important;
  }
</style>
<style lang="less" scoped>
  .login {
    background: url("../../assets/loginbg.png") no-repeat top center fixed;
    background-size: 100% 410px;
    display: flex;
    justify-content: center;
    height: 100%;
    position: relative;
    overflow: hidden;
    background-color: #fff;

    .content {
      position: absolute;
      top: 474px;

      .user-info-bg,
      .user-info-username,
      .user-info-pwd,
      .user-info-pwd-message {
        width: 600px;
        height: 96px;
        border-radius: 8px;
        background-color: rgba(241, 241, 241, 1);
        display: flex;
        align-items: center;
        padding-left: 40px;
      }
      .user-info-pwd,
      .user-info-pwd-message {
        margin-top: 30px;
      }

      .form-input {
        width: 462px;
        border-radius: 16px;
        background-color: rgba(241, 241, 241, 1);
        font-size: 28px;
        border: none;
        margin-bottom: 0;
        line-height: normal;
        padding: 0 0 0 40px;
      }

      .user-info-pwd-message {
        .form-input {
          width: 362px;
        }
        .get-validate-code {
          width: 128px;
          height: 56px;
          line-height: 56px;
          border-radius: 4px;
          background-color: rgba(81, 104, 255, 1);
          color: rgba(255, 255, 255, 1);
          padding: 0;
          text-align: center;
          vertical-align: text-bottom !important;
          position: absolute;
          right: 40px;
          font-size: 30px;
          &:active {
            background: #3c56e3;
          }
        }
      }
      .jeicon-eye {
        position: absolute;
        right: 28px;
        font-size: 24px;
      }
      .jeicon-eye-close {
        position: absolute;
        right: 30px;
        font-size: 30px;
      }

      input::-webkit-input-placeholder {
        color: #aab2bd;
      }

      .pwd {
        margin-top: 30px;
        display: flex;
        justify-content: space-between;
        width: 100%;
        height: 40px;
        line-height: 40px;
        color: rgba(81, 104, 255, 1);

        label {
          font-size: 28px;
        }
      }

      .login-btn {
        margin-top: 96px;
        width: 600px;
        height: 96px;
        border-radius: 16px;
        background-color: #536dfe;
        box-shadow: 0px 5px 12px 0px rgba(83, 109, 254, 0.44);
        // line-height: 66px;
        color: rgba(255, 255, 255, 1);
        font-size: 36px;
        &:active {
          background: #3c56e3;
        }
      }

      .register-btn {
        margin-top: 84px;
        height: 44px;
        line-height: 44px;
        color: rgba(83, 109, 254, 1);
        font-size: 32px;
        text-align: justify;
        display: flex;
        justify-content: center;
        //width: 100%;
      }

      .other-login {
        margin-top: 90px;
        padding-left: 80px;
        padding-right: 80px;
        display: flex;
        margin-bottom: 68px;
        justify-content: space-around;
        .jeicon {
          font-size: 60px;
          color: #cfcfcf;
        }
      }
    }

    .logon-content {
      width: 100%;
      text-align: center;
      .logo {
        height: 138px;
        position: relative;
        top: 120px;
        text-align: center;
      }
    }
  }

  .jeicon {
    color: #cfcfcf;
    font-size: 32px;
  }

  .user-list-span {
    transform: rotate(90deg);
    line-height: 1.28rem;
    text-align: center;
    float: right;
    height: 100%;
    // width:100%;
  }
</style>
